package com.ch12;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * 随机产生1-n的m个数
 * 
 * @author Linxiaozhi
 * 
 */
public class RandomGenerate {
	public static void main(String[] args) {
		if (args.length == 0) {
			System.out.println("useage: java com.ch12.RandomGenerate  70000000 10000000 ");
			//f1(20, 100);
			//f0(m, n);	
			return;
		}
		int m = Integer.parseInt(args[0]);
		int n = Integer.parseInt(args[1]);
		System.out.println("m:" + m + ",n:" + n);
		long l1 = System.currentTimeMillis();
		try {
			PrintWriter pw = new PrintWriter("d:/input.txt");
			f1(m, n, pw);
			pw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		long l2 = System.currentTimeMillis();
		System.out.println("time:" + (l2 - l1));

	}

	static int randInt(int i, int j, Random rand) {
		if (i < j)
			return i + rand.nextInt(j - i + 1);
		else if (i > j)
			return j + rand.nextInt(i - j + 1);
		return i;
	}

	static void f0(int m, int n) {
		int select = m;
		int remaining = n;
		Random rand = new Random(System.currentTimeMillis());
		for (int i = 0; i < n; i++) {
			if (rand.nextInt(remaining) < select) {
				System.out.println(m - select + 1 + ":" + i);
				select--;
			}
			remaining--;
		}

	}

	static void f1(int m, int n) {
		int[] array = new int[n];
		Random rand = new Random(System.currentTimeMillis());
		for (int i = 0; i < n; i++)
			array[i] = i + 1;
		for (int i = 0; i < m; i++) {
			int j = randInt(i, n - 1, rand);
			int temp = array[j];
			array[j] = array[i];
			array[i] = temp;
		}

		for (int i = 0; i < m; i++) {
			System.out.println(i + 1 + ":" + array[i]);
		}
	}

	static void f1(int m, int n, PrintWriter pw) {
		int[] array = new int[n];
		Random rand = new Random(System.currentTimeMillis());
		for (int i = 0; i < n; i++)
			array[i] = i + 1;
		for (int i = 0; i < m; i++) {
			int j = randInt(i, n - 1, rand);
			int temp = array[j];
			array[j] = array[i];
			array[i] = temp;
		}

		for (int i = 0; i < m; i++) {
			pw.println(array[i]);

		}
		pw.flush();
	}

}
